<?php

namespace App\Http\Controllers;

use App\Http\Model\Hint;
use App\Http\Model\OutJson;
use App\Http\Model\RoomUser;
use App\Http\Model\User;
use App\Http\Services\GroupChatMsgServices;
use App\Http\Services\MsgServices;
use App\Http\Services\Queue\QueueServices;
use App\Http\Services\RoomMsgServices;
use App\Http\Services\RoomUserServices;
use App\Http\Services\UnionServices;
use App\Http\Services\UserServices;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Lib\Response;

class UnionController extends BaseController
{
    private $room_msg_services;
    private $services_msg;
    private $services_users;
    private $services_union;
    private $groupChatMsgServices;

    public function __construct()
    {
        $this->room_msg_services = new RoomMsgServices();
        $this->services_msg = new MsgServices();
        $this->services_users = new UserServices();
        $this->services_union = new UnionServices();
        $this->groupChatMsgServices = new GroupChatMsgServices();
    }

    //cms创建 修改公会
    public function cmsCreatedUnion(Request $request)
    {
        $user_id = $request->input("user_id");
        if (!$user_id) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $name = $request->input('name') ?? '';
        $portrait = $request->input('portrait') ?? '';
        $sort = $request->input('sort') ?? 1;
        $notice = $request->input('notice') ?? '';
        $desc = $request->input('desc') ?? '';
        $settleType = $request->input('settle_type') ?? '';
        $unionCompany = $request->input('union_company', '');
        $unionBankName = $request->input('union_bank_name', '');
        $unionBankNo = $request->input('union_bank_no', '');
        $rewardType = (int) $request->input('reward_type', 0);
        if($settleType == 2) {
            if(empty($unionCompany) || empty($unionBankName) || empty($unionBankNo)) {
                Response::returnResult(Hint::ERROR, '对公结算信息为空');
            }
        }

        $res = $this->services_union->createUnion($user_id, $name, $portrait, $sort, $notice, $desc, $settleType, $unionCompany, $unionBankName, $unionBankNo, $rewardType);
        if ($res) {
            Response::returnResult(Hint::SUCCESS, $res);
        }
        Response::returnResult(Hint::ERROR);
    }

    //cms创建 修改公会
    public function cmsUpdateUnion(Request $request)
    {
        $data = $request->input();
        if (!$data['id']) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $res = $this->services_union->updateUnion($data);
        if ($res) {
            Response::returnResult(Hint::SUCCESS, $res);
        }
        Response::returnResult(Hint::ERROR);
    }


    //cms 添加公会房间
    public function cmsAddUnionRoom(Request $request)
    {
        $union_id = $request->input("union_id");
        $adminName = $request->input("admin_name");
        if (!$union_id) {
            Response::returnResult(Hint::PARAM_ERROR);//businessOptions
        }
        return $this->services_union->createRoomByCBD($union_id,1,$adminName);
    }

    //房间绑定公会
    public function roomJoinUnion(Request $request)
    {
        $union_id = $request->input("union_id");
        $room_id = $request->input("room_id");
        if (!$union_id || !$room_id) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $res = $this->services_union->joinRoomByCBD($union_id, $room_id);
        if ($res) {
            Response::returnResult(Hint::SUCCESS, $res);
        }
        Response::returnResult(Hint::ERROR);
    }

    //公会列表
    public function unionList(Request $request)
    {
        $user_info = $this->services_users->get_current_user();
        $user_id = $user_info['user_id'];
        $data['data'] = $this->services_union->getList($request->input());
        $data['union_info'] = $this->services_union->getUserUnionInfo($user_id);
        Response::returnResult(Hint::SUCCESS, $data);
    }

    //用户申请公会
    public function userApplyUnion(Request $request)
    {
        $union_id = $request->input('union_id') ?? 0;
        $user_info = $this->services_users->get_current_user();
        $user_id = $user_info['user_id'];
        if ($user_info['active_certify'] == 0) {
            Response::returnResult(Hint::USER_NOT_CERTIFICATION);
        }
        $audit_union_user_ids = $this->services_union->getAuditUnionUserIds($union_id);
        if (!$audit_union_user_ids) {
            Response::returnResult(Hint::ERR_FAIL);
        }
        $res = $this->services_union->applyUnion($user_id, $union_id);
        if ($res['code']==Hint::SUCCESS || $res['code']==Hint::SAME_TIME_NOT_REPEAT) {
            $data = $res['data'];
            //发送消息
            $status = 0;//入会申请
            //查询公会可审批用户id
            for ($i = 0; $i < count($audit_union_user_ids); $i++) {
                $this->services_msg->applyJoinUnionMsg($data['union_id'], $audit_union_user_ids[$i], $data['apply_user_id'], $status);
            }
        }
        Response::returnResult($res['code'], $res['data'], $res['msg']);
    }
    //用户申请公会
    public function userApplyUnionV2(Request $request)
    {
        $union_id = $request->input('union_id') ?? 0;
        $user_info = $this->services_users->get_current_user();
        $user_id = $user_info['user_id'];
        if ($user_info['active_certify'] == 0) {
            Response::returnResult(Hint::USER_NOT_CERTIFICATION);
        }

        $audit_union_user_ids = $this->services_union->getAuditUnionUserIds($union_id);
        if (!$audit_union_user_ids) {
            Response::returnResult(Hint::ERR_FAIL);
        }
        $res = $this->services_union->applyUnion($user_id, $union_id);
        if ($res['code']==Hint::SUCCESS || $res['code']==Hint::SAME_TIME_NOT_REPEAT) {
            $data = $res['data'];
            //发送消息
            $status = 0;//入会申请
            //查询公会可审批用户id
            for ($i = 0; $i < count($audit_union_user_ids); $i++) {
                $this->services_msg->applyJoinUnionMsg($data['union_id'], $audit_union_user_ids[$i], $data['apply_user_id'], $status);
            }
        }

        Response::returnResult($res['code'], $res['data'], $res['msg']);
    }
    //申请公会列表
    public function userApplyUnionList(Request $request)
    {
        $union_id = $request->input('union_id') ?? 0;
        $user_info = $this->services_users->get_current_user();
        $user_id = $user_info['user_id'];
        if ($user_info['active_certify'] == 0) {
            Response::returnResult(Hint::USER_NOT_CERTIFICATION);
        }
        $audit_union_user_ids = $this->services_union->getAuditUnionUserIds($union_id);
        if (!$audit_union_user_ids) {
            Response::returnResult(Hint::ERR_FAIL);
        }
        $res = $this->services_union->applyUnionlist($user_id, $union_id);

        Response::returnResult($res['code'], $res['data'], $res['msg']);
    }
    public function userCountApplyUnionList(Request $request)
    {
        $union_id = $request->input('union_id') ?? 0;
        $user_info = $this->services_users->get_current_user();
        $user_id = $user_info['user_id'];
        if ($user_info['active_certify'] == 0) {
            Response::returnResult(Hint::USER_NOT_CERTIFICATION);
        }

        $res = $this->services_union->applyCountUnionlist($user_id, $union_id);

        Response::returnResult($res['code'], $res['data'], $res['msg']);
    }

    //审批用户入会
    public function userApplyUnionStatus(Request $request)
    {
        $apply_user_id = $request->input('apply_user_id') ?? 0;
        $status = $request->input('status') ?? 2;//1同意2拒绝
        $user_info = $this->services_users->get_current_user();
        $user_id = $user_info['user_id'];
        $res = $this->services_union->editApplyUnionStatus($user_id, $apply_user_id, $status);
        if ($res['code'] == 0 && $status==1) {
            $data = $res['data'];
            $union_id = $data['union_id'];
            $audit_union_user_ids = $this->services_union->getAuditUnionUserIds($union_id);
            if (!$audit_union_user_ids) {
                return $res;
            }
            //发送消息
            $audit_union_user_ids[] = $data['apply_user_id'];
            for ($i = 0; $i < count($audit_union_user_ids); $i++) {
                $this->services_msg->applyJoinUnionMsg($union_id, $audit_union_user_ids[$i], $data['apply_user_id'], $status, $user_info['nickname']);
            }
        }else if($res['code'] ==0 && $status==2){
            $this->services_msg->applyJoinUnionMsg($res['data']['union_id'],$apply_user_id, $user_id,$status, $user_info['nickname']);
        }
        Response::returnResult($res['code'], $res['data'], $res['msg']);
    }


    //我的公会
    public function myUnion(Request $request)
    {
        $union_id = $request->input('union_id', 0);
        $user_info = $this->services_users->get_current_user();
        $user_id = $user_info['user_id'];
        $phone = $user_info['phone'];
        if (!$user_id) {
            Response::returnResult(Hint::ERR_FAIL);
        }

        $result = $this->services_union->getUserUnion($user_id, $union_id,$phone);
        $result['data']['consumer'] = $this->services_union->showUnionFinanceALLHistory($union_id);
        $result['data']['consumer'] = $result['data']['consumer']??"0";
        Response::returnResult($result['code'], $result['data'], $result['msg']);
    }

    //我的公会
    public function myInfo(Request $request)
    {
        $data = $this->services_union->getUserMyUnion($request);

        Response::returnResult(Hint::SUCCESS, $data);

    }

    //获取指定用户公会
    public function getUserUnion(Request $request)
    {
        $userId = (int) $request->input('user_id');
        if(empty($userId)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $result['user_id'] = $userId;
        $result['union_id'] = 0;

        $data = $this->services_union->getUserUnionInfo($userId);
        if(!empty($data)) {
            $result['union_id'] = (int) $data['un_id'];
            $result['un_user_id'] = (int) $data['un_user_id'];
            $result['settle_type'] = (int) $data['settle_type'];
        }

        Response::returnResult(Hint::SUCCESS, $result);
    }

    //公会成员
    public function myUnionUserList(Request $request)
    {
        $union_id = $request->input('union_id') ?? 0;
        $search = $request->input('search');
        $page = !empty((int)$request->input('page_index')) && $request->input('page_index') >= 0 ? (int)$request->input('page_index') : 0;
        $page_size = !empty((int)$request->input('page_size')) && $request->input('page_size') > 0 ? (int)$request->input('page_size') : 10;
        $user_info = $this->services_users->get_current_user();
        $user_id = $user_info['user_id'];
        $res = $this->services_union->getUnionUserListV2($user_id, $search,$union_id,$page,$page_size);
//        $res = $this->services_union->getUnionUserList($user_id, $search,$union_id);
        Response::returnResult(Hint::SUCCESS, $res);
    }

    //公会长设置分成比例时前置接口,若在缓存期则不允许更改
    public function checkUnionUserRate(Request $request)
    {
        $userInfo = $this->services_users->get_current_user(); //登录信息
        if(empty($userInfo)) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        $userid = $request->input('user_id',0);//公会成员id
        $union_id = $request->input('union_id',0); //公会id
        $admin_union_userid = $userInfo['user_id'];//公会长id
        $res = $this->services_union->checkUnionUserRate($union_id,$userid,$admin_union_userid);
        Response::returnResult($res['code'], $res['data'], $res['msg']);
    }

    //公会长设置公会成员费率
    public function setUnionUserRate(Request $request)
    {
        $admin_uionuser_info = $this->services_users->get_current_user(); //登录信息
        if(empty($admin_uionuser_info)) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        $union_id = empty($request->input('union_id')) ? 0 : $request->input('union_id'); //公会id
        $user_rate = $request->input('rate');//用户费率
        $userid = empty($request->input('user_id')) ? 0 : $request->input('user_id');//成员id
        $admin_uinonuser_id = $admin_uionuser_info['user_id'];//公会长id
        $res = $this->services_union->setUinonUserRate($admin_uinonuser_id,$userid,$union_id,$user_rate);//设置公会成员费率
        Response::returnResult($res['code'], $res['data'], $res['msg']);
    }

    //公会成员对私确认-发送验证码
    public function unionUserSmscode(Request $request)
    {
        $userid = $request->post('user_id',0);//公会成员id
        $sms_token = $request->post('sms_token','');//短信验证token
        write_log('change_union_rate','INFO 参数',['sms_token'=>$sms_token,'all'=>$request->all(),'UA'=>$request->userAgent()]);
        //调用sms发送接口
        $res = $this->services_union->sendSmsCode($userid,$sms_token);
        Response::returnResult($res['code'], $res['data'], $res['msg']);
    }

    //公会成员确认对私费率调整
    public function unionUserConfirm(Request $request)
    {
        $userid = $request->input('user_id',0);//公会成员id
        $sms_code = $request->input('sms_code',0);//短信验证码
        //确认对私调整
        $res = $this->services_union->confirmRate($userid,$sms_code);
        Response::returnResult($res['code'], $res['data'], $res['msg']);
    }

    //离开公会  解散公会
    public function quitUnion(Request $request)
    {
        Response::returnResult(Hint::NOT_ALLOWED, [],'退会请联系公会长');

        $user_info = $this->services_users->get_current_user();
        $user_id = $user_info['user_id'];
        $res = $this->services_union->quitMyUnion($user_id);
        if ($res['code'] == 0) {
            $data = $res['data'];
            $audit_union_user_ids = $this->services_union->getAuditUnionUserIds($data['union_id']);
            $audit_union_user_ids[] = $user_id;
            for ($i = 0; $i < count($audit_union_user_ids); $i++) {
                $this->services_msg->quitUnionMsg($data['union_id'], $audit_union_user_ids[$i], $user_id);
            }
        }
        Response::returnResult($res['code'], $res['data'], $res['msg']);
    }

    //踢出公会
    public function kickUnionUser(Request $request)
    {
        $kick_user_id = $request->input('kick_user_id', 0);
        $user_info = $this->services_users->get_current_user();
        $user_id = $user_info['user_id'];//指定用户
        $res = $this->services_union->kickUnionUser($user_id, $kick_user_id);
        if ($res['code'] == 0) {
            //发送消息
            $type = 1;
            $this->services_msg->removeUnionMsg($res['data']['union_id'], $kick_user_id, $kick_user_id, $user_info['nickname'], $type);
        }
        Response::returnResult($res['code'], $res['data'], $res['msg']);
    }
    //获取职位列表+已任命人数
    public function getRoleList(Request $request)
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_union, 'getRoleList', $this->requestData);

        } while (false);

        $this->responseData();
    }

    //取消公会房间任命
    public function cancelUnionRoomRole(Request $request)
    {
        $user_info = $this->services_users->get_current_user();
        $user_id = $user_info['user_id'];//操作用户
        $cancel_user_id = $request->input('cancel_user_id', 0);
        $room_id = $request->input('room_id', 0);
        $result = $this->services_union->cancelUnionRoomRole($user_id, $cancel_user_id, $room_id);
        Response::returnResult($result['code'], $result['data'], $result['msg']);
    }

    //任命房间管理员
    public function acceptRoomRole(Request $request)
    {
        $assign_user_id = $request->input('assign_user_id', 0);
        $room_id = $request->input('room_id', 0);
        $user_info = $this->services_users->get_current_user();
        $user_id = $user_info['user_id'];//操作用户
        $role_type = 2;//超管
        $result = $this->services_union->acceptRoomRole($user_id, $assign_user_id, $room_id, $role_type);
        Response::returnResult($result['code'], $result['data'], $result['msg']);
    }

    //查看公会房间列表
    public function showUnionRoom(Request $request)
    {
        $startDay=$request->get('startDay')??'';
        $endDay=$request->get('endDay')??'';
        $Daytype=$request->get('daytype')??'';
//        if(empty($endDay)){
//            $Daytype=$request->get('daytype')??'1';
//        }
        $page = !empty((int)$request->input('page_index')) && $request->input('page_index') >= 0 ? (int)$request->input('page_index') : 0;
        $page_size = !empty((int)$request->input('page_size')) && $request->input('page_size') > 0 ? (int)$request->input('page_size') : 8;
        if($page_size>10){
            $page_size=8;
        }
        $day = date('Y-m-d', time());
        if($startDay==$day && $endDay== $day){
            $Daytype=$request->get('daytype')??'1';
        }
        $adminId = $request->get('admin_id');
        if(!empty($adminId)){
            $user_info = $this->services_users->getUserData($adminId,false);
        }else{
            $user_info = $this->services_users->get_current_user();
        }
        $this->saveUserCookieLog($user_info);

        if (empty($user_info['user_id'])) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        // write_log('union', 'unionLog showUnionRoom', [$user_info,$request->all()]);

        $user_id = $user_info['user_id'];
        $res = $this->services_union->getUnionRoom($user_id,$startDay,$endDay,$Daytype,$page,$page_size);
        Response::returnResult($res['code'], $res['data'], $res['msg']);
    }

    public function roomTotalStream(Request $request) {
        $room_id = $request->get('room_id')??'';
        if (empty($room_id)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }

        $res = $this->services_union->getUnionRoomTotalStream($room_id);

        Response::returnResult($res['code'], $res['data'], $res['msg']);
    }
//    公会流水
    public function showUnionRoomV2(Request $request)
    {
        $startDay=$request->get('startDay')??'';
        $endDay=$request->get('endDay')??'';
        $Daytype=$request->get('daytype')??'';
//        if(empty($endDay)){
//            $Daytype=$request->get('daytype')??'1';
//        }
        $day = date('Y-m-d', time());
        if($startDay==$day && $endDay== $day){
            $Daytype=$request->get('daytype')??'1';
        }
        $adminId = $request->get('admin_id');
        if(!empty($adminId)){
            $user_info = $this->services_users->getUserData($adminId,false);
        }else{
            $user_info = $this->services_users->get_current_user();
        }
        $this->saveUserCookieLog($user_info);

        if (empty($user_info['user_id'])) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        // write_log('union', 'unionLog showUnionRoom', [$user_info,$request->all()]);
        $user_id = $user_info['user_id'];
        $res = $this->services_union->getUnionRoomV2($user_id,$startDay,$endDay,$Daytype);
        Response::returnResult($res['code'], $res['data'], $res['msg']);
    }

    public function showUnionRoomV2Days(Request $request)
    {
        $startDay=$request->get('startDay')??'';
        $endDay=$request->get('endDay')??'';
        $Daytype=$request->get('daytype')??'';
//        if(empty($endDay)){
//            $Daytype=$request->get('daytype')??'1';
//        }
        $day = date('Y-m-d', time());
        if($startDay==$day && $endDay== $day){
            $Daytype=$request->get('daytype')??'1';
        }
        $adminId = $request->get('admin_id');
        if(!empty($adminId)){
            $user_info = $this->services_users->getUserData($adminId,false);
        }else{
            $user_info = $this->services_users->get_current_user();
        }
        $this->saveUserCookieLog($user_info);

        if (empty($user_info['user_id'])) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
//        write_log('unionDays', 'unionLog showUnionRoom', [$user_info,$request->all()]);
        $user_id = $user_info['user_id'];
        write_log('unionDays', 'unionLog showUnionRoom', [$user_id,$startDay,$endDay,$Daytype]);
        $res = $this->services_union->getUnionRoomV2Days($user_id,$startDay,$endDay,$Daytype);
        Response::returnResult($res['code'], $res['data'], $res['msg']);
    }
    //获取用户信息&公会信息
    public function getUserInfoOrUnionInfo(Request $request)
    {
        $user_info = $this->services_users->get_current_user();
        $user_id = $user_info['user_id'];
        $union_info = $this->services_union->getUserUnionInfo($user_id);
        $res['user_info'] = $user_info;
        $res['union_info'] = $union_info;
        Response::returnResult(Hint::SUCCESS, $res);
    }

    //客户端查看公会信息
    public function showUnionInfo(Request $request)
    {
        $union_id = $request->input('union_id', 0);
        $res['union_info'] = $this->services_union->getUnionInfo($union_id);
        $res['room_list'] = $this->services_union->getUnionRoomList($union_id);
        $union_user = $this->services_union->getAllUnionUserList($union_id);
        $res['user_count'] = count($union_user['role_user']) + count($union_user['user']);
        $user_info = $this->services_users->get_current_user();
        $user_id = $user_info['user_id'];
        $res['union_url'] = '/html/union/html/union_info.html';
        $res['level'] = $res['union_info']['level'] ?? 1;
        //判断是否申请
        $is_apply = $this->services_union->checkJoinUnionToUser($user_id, $union_id);//当前用户公会信息
        $res['inner_status'] = $is_apply['inner_status'];
        Response::returnResult(Hint::SUCCESS, $res);
    }

    public function myUnionUrl(Request $request)
    {
        $user_info = $this->services_users->get_current_user();
        $data['union_url'] = '/html/union/html/union_search_union.html';
        Response::returnResult(Hint::SUCCESS, $data);
    }

    //跟新公会细则
    public function updateRule(Request $request)
    {
        $user_info = $this->services_users->get_current_user();
        $user_id = $user_info['user_id'];
        $result = $this->services_union->updateRule($user_id);
        Response::returnResult($result['code'], $result['data'], $result['msg']);
    }

    //离开公会  解散公会
    public function cmsDissolveUnion(Request $request)
    {
        $user_id = $request->input('user_id');
        $unionData = $this->services_union->delUnion($user_id);
        $unionId = $unionData['union_id'] ?? 0;
        $group_id = $unionData['group_id'];
        if (!empty($unionId)) {
            $this->groupChatMsgServices->groupSendUnionDissolveMsg($user_id, $group_id ,'你所在的公会已解散' );
        }
        Response::returnResult(Hint::SUCCESS);
    }

    //公会流水统计
    public function getUnionRoomFinance(Request $request)
    {
        $adminId = $request->get('admin_id');
        if(!empty($adminId)){
            $user_info = $this->services_users->getUserData($adminId,false);
        }else{
            $user_info = $this->services_users->get_current_user();
        }
        // write_log('union', 'unionLog getUnionRoomFinance', [$user_info,$request->all()]);
        $this->saveUserCookieLog($user_info);
        if (empty($user_info['user_id'])) {
            Response::returnResult(Hint::LOGIN_OUT);
        }

        $user_id = $user_info['user_id'];
        $startDay = empty($request->input('startDay')) ? date('Y-m-d 00:00:00', time()) : $request->input('startDay') . '00:00:00';
        $endDay = empty($request->input('endDay')) ? date('Y-m-d 23:59:59', time()) : $request->input('endDay') . '23:59:59';
        $room_id = $request->input('room_id') ?? 0;
        $search_user_id = $request->input('user_id');
        return $this->services_union->showUnionRoomFinance($user_id, $room_id, $startDay, $endDay, $search_user_id);//房间消费
    }

    //公会流水统计
    public function getUnionRoomFinanceV2(Request $request)
    {
        $adminId = $request->get('admin_id');
        if(!empty($adminId)){
            $user_info = $this->services_users->getUserData($adminId,false);
        }else{
            $user_info = $this->services_users->get_current_user();
        }

        // write_log('union', 'unionLog getUnionRoomFinanceV2', [$user_info,$request->all()]);
        $this->saveUserCookieLog($user_info);

        if (empty($user_info['user_id'])) {
            Response::returnResult(Hint::LOGIN_OUT);
        }

        $result = $this->services_union->showUnionRoomFinanceV2($user_info['user_id']);//房间消费

        Response::returnResult($result['code'], $result['data'], $result['msg']);
    }

    public function getUnionConsumerUser(Request $request)
    {
        $startTime = microtime(true);
        $adminId = $request->get('admin_id');
//        $Daytype = $request->get('daytype');
        $startDay = $request->get('startDay') ?? '';
        $endDay = $request->get('endDay') ?? '';
        if (empty($startDay)) {
            $Daytype = $request->get('daytype') ?? '1';
        }

        $day = date('Y-m-d', time());
        if ($startDay == $day && $endDay == $day) {
            $Daytype = $request->get('daytype') ?? '1';
        }
        if (!empty($adminId)) {
            $user_info = $this->services_users->getUserData($adminId, false);
        } else {
            $user_info = $this->services_users->get_current_user();
        }
        // write_log('union', 'unionLog getUnionConsumerUser', [$user_info,$request->all()]);
        $this->saveUserCookieLog($user_info);
        if (empty($user_info['user_id'])) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        $user_id = $user_info['user_id'];
        $room_id = $request->input('room_id',0);
        $search_user_id = $request->input('user_id');
        $page = $request->input('page',1);
        $limit  = 20; //页面分页条数
//        if(empty($Daytype)){
//            $type = $request->input('type')??0; //0收礼，1送礼
//        }else{
        $type = $request->input('type')??1; //0收礼，1送礼
//        }
        if($type == 0){
            $startDay = empty($request->input('startDay')) ? date('Y-m-d 00:00:00', time()) : $request->input('startDay') . ' 00:00:00';
            $endDay = empty($request->input('endDay')) ? date('Y-m-d 23:59:59', time()) : $request->input('endDay') . ' 23:59:59';
            $result = $this->services_union->showUnionConsumerLog($user_id, $room_id, $startDay, $endDay, $search_user_id,$page,$limit);//房间消费
        }else{
            $result = $this->services_union->showUnionConsumerLogByReceiveUserV2($user_id, $room_id, $startDay, $endDay, $search_user_id,$page,$limit,$Daytype);//房间消费
        }

        $endTime = microtime(true);
        $executionTime = round($endTime - $startTime, 3);
        write_log('unionTimes', 'getUnionConsumerUser execution time', ['time' => $executionTime . 's']);
        Response::returnResult($result['code'], $result['data'], $result['msg']);
    }

    public function getConsumerUserList(Request $request)
    {
        $adminId = $request->get('admin_id');
        if(!empty($adminId)){
            $user_info = $this->services_users->getUserData($adminId,false);
        }else{
            $user_info = $this->services_users->get_current_user();
        }

        // write_log('union', 'unionLog getConsumerUserList', [$user_info,$request->all()]);
        $this->saveUserCookieLog($user_info);

        $user_id = $user_info['user_id'];
        $startDay = empty($request->input('startDay')) ? date('Y-m-d 00:00:00', time()) : $request->input('startDay') . ' 00:00:00';
        $endDay = empty($request->input('endDay')) ? date('Y-m-d 23:59:59', time()) : $request->input('endDay') . ' 23:59:59';
        $room_id = $request->input('room_id') ?? 0;
        $search = $request->input('search');
        return $this->services_union->showUnionConsumerUserList($user_id, $room_id, $startDay, $endDay, $search);
    }

    public function getHrefUrl()
    {
        $data['union_url'] = '/html/union/html/union_info.html';
        Response::returnResult(Hint::SUCCESS, $data);
    }

    public function cmsKickUnionUser()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_union, 'cmsKickUnionUser', $this->requestData);

        } while (false);

        $this->responseData();

    }

    //来来语音116号需求-公会体系迭代
    /**
     *  客户端创建公会
     */
    public function appCreateUnion(Request $request){
        do {
            $params = $request->all();
            write_log('create_union','INFO 参数',$params);
            if(empty($params)){
                Response::returnResult(Hint::PARAM_ERROR);
            }
            $res = $this->services_union->appCreateUnion($params);

        } while (false);
        Response::returnResult($res['code'], $res['data'], $res['msg']);
    }

    /**
     * 公告列表
     */
    public function noticeList(){
        do {
            if (!$this->checkRequest()) {
                break;
            }
            $this->callCommon($this->services_union, 'noticeList', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 添加公告
     */
    public function addNotice(){
        do {
            if (!$this->checkRequest()) {
                break;
            }
            $this->callCommon($this->services_union, 'addNotice', $this->requestData);

        } while (false);

        $this->responseData();
    }
    /**
     * 删除公告
     */
    public function delNotice(){
        do {
            if (!$this->checkRequest()) {
                break;
            }
            $this->callCommon($this->services_union, 'delNotice', $this->requestData);

        } while (false);

        $this->responseData();
    }
    /**
     * 设置公会相关信息
     */
    public function setUnionInfo(){
        do {
            if (!$this->checkRequest()) {
                break;
            }
            $this->callCommon($this->services_union, 'setUnionInfo', $this->requestData);

        } while (false);


        if(is_string($this->responseData)) $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    /**
     * 解散公会校验会长身份，并发短信
     */
    public function checkPresidentStatus(){
        do {
            if (!$this->checkRequest()) {
                break;
            }
            $this->callCommon($this->services_union, 'checkPresidentStatus', $this->requestData);

        } while (false);

        if(is_string($this->responseData)) $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    /**
     * 解散公会校验验证码
     */
    public function checkPresidentCode(){
        do {
            if (!$this->checkRequest()) {
                break;
            }
            $this->callCommon($this->services_union, 'checkPresidentCode', $this->requestData);

        } while (false);

        if(is_string($this->responseData)) $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    /**
     * app 解散公会
     */
    public function appDissolveUnion(){
        do {
            if (!$this->checkRequest()) {
                break;
            }
            $res = $this->callCommon($this->services_union, 'appDissolveUnion', $this->requestData,false);
            if($res['code'] == 0){
                $unionId = $res['data']['union_id'] ?? 0;
                $group_id = $res['data']['group_id'];
                if (!empty($unionId)) {
                    $this->groupChatMsgServices->groupSendUnionDissolveMsg($this->requestData['user_id'], $group_id ,'你所在的公会已解散' );
                }
            }

        } while (false);

        if(is_string($this->responseData)) $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    //公会房间管理员/成员列表
    public function getRoomUserList()
    {
        do {
            if (!$this->checkRequest()) {
                break;
            }
            $this->callCommon($this->services_union, 'getRoomUserList', $this->requestData);
        } while (false);

        if(is_string($this->responseData)) $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    public function cmsGetGrade(Request $request)
    {
        $input = $request->post();

        $data = $this->services_union->getGrade($input);

        Response::returnResult(Hint::SUCCESS, $data);
    }

    public function inviteJoin(){
        do {
            if (!$this->checkRequest()) {
                break;
            }
            $res = $this->callCommon($this->services_union, 'inviteJoin', $this->requestData ,false);
            if($res['code'] == 0){
                $this->services_msg->inviteJoinUnionMsg($res['data']);
            }

        } while (false);

        if(is_string($this->responseData)) $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    //通过uuid 搜索公会成员
    public function searchUserByUuid(Request $request){
        $union_id = $request->input("union_id", 0);
        $room_id = $request->input("room_id", 0);
        $uuid = $request->input("uuid", 0);

        $user = $this->services_union->searchUserByUuid($union_id,$uuid);
        if ($user == null) {
            Response::returnResult(Hint::USER_NOT_EXIST);
        }

        $role = (new RoomUserServices())->getRoleById($room_id, $user['user_id']);
        list($role_id, $role_name) = $this->services_union->getUnionRoleById($union_id, $user['user_id']);

        $ret['room_id'] = $room_id;
        $ret['role_id'] = $role_id;
        $ret['role_name'] = $role_name;
        $ret['is_admin'] = $role>1;
        $ret['user_id'] = $user['user_id'];
        $ret['uuid'] = $user['uuid'];
        $ret['nickname'] = $user['nickname'];
        $ret['gender'] = $user['gender'];
        $portrait = json_decode($user['portrait'], true);
        $ret['avatar'] = build_image($portrait[0]??'');

        Response::returnResult(Hint::SUCCESS, $ret);
    }

    /**
     * 公会流水总是出现取不到用户信息的情况，记录一下日志，方便排查问题
     */
    public function saveUserCookieLog($user_info){
        if(empty($user_info)){
            $log['cookie'] = $_COOKIE['user_token'] ?? "";
            $log['HTTP_REQUESTED_TOKEN'] = $_SERVER['HTTP_REQUESTED_TOKEN'] ?? "";
            $log['HTTP_TOKEN'] = $_SERVER['HTTP_TOKEN'] ?? "";
            $userModel = new User();
            $token = $userModel->getToken();
            $uid = $userModel->get_cache_token_userid($token);
            $log['token'] = $token;
            $log['uid'] = $uid;
            write_log('union', 'unionLog saveToken', $log);
        }
    }

    /**
     * 统计公会房间内结算流水
     */
    public function getUnionRoomDjBill(Request $request)
    {
        $adminId = $request->get('admin_id'); //公会长用户id
        $roomid = $request->get('room_id'); //房间id
        if(!empty($adminId)){
            $user_info = $this->services_users->getUserData($adminId,false);
        }else{
            $user_info = $this->services_users->get_current_user();
        }
        $this->saveUserCookieLog($user_info);

        if (empty($user_info['user_id'])) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        //搜索条件
        $startDate = $request->get('startDate',date('Y-m-d H:i:s',time()));
        $endDate = $request->get('endDate',date('Y-m-d H:i:s',time()));
        $result = $this->services_union->showUnionRoomBill($user_info['user_id'],$startDate,$endDate,$roomid);//房间内公会结算流水
        if (empty($result['data']))
        {
            $result['data'] = 0;
        }
        $result['data'] = (int)$result['data'][0]['total'];
        Response::returnResult($result['code'], $result['data'], $result['msg']);
    }
}
